package com.cheys.webapp.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.cheys.webapp.model.Admin;
import com.cheys.webapp.model.Case;
import com.cheys.webapp.model.WebSite;
import com.cheys.webapp.service.AdminService;
import com.cheys.webapp.service.CaseService;
import com.cheys.webapp.util.DateUtil;
import com.cheys.webapp.util.FileHelper;
import com.cheys.webapp.util.HTMLCreatorListener;
import com.cheys.webapp.util.LogUtil;
import com.cheys.webapp.util.PassCode;
import com.cheys.webapp.util.StringUtil;
import com.cheys.webapp.util.TypeHelper;

@Controller
@RequestMapping("/admin")
public class AdminController {
	private final Logger logger = LogUtil.getLogger(AdminController.class);
	@Autowired
	private AdminService adminService;
	@Autowired
	private CaseService caseService;
	
	/**
	 * 验证码生成逻辑处理
	 * @param response
	 * @param request
	 */
	@RequestMapping("/getcode")
	public void getcode(HttpServletResponse response,HttpServletRequest request){
		logger.info("生成验证码信息");
		try {
			request.getSession().removeAttribute("randomcode");
			new PassCode().createPasscode(response, request);
			logger.info("验证码信息生成完毕");
		} catch (IOException e) {
			logger.debug("生成验证码信息异常"+e);
		}
	}
	/**
	 * 登录逻辑处理
	 * @param admin
	 * @param response
	 * @param request
	 */
	@RequestMapping("/login")
	public void login(Admin admin,HttpServletResponse response,HttpServletRequest request){
		logger.info(">>处理管理员登陆逻辑");
		long starttime = System.currentTimeMillis();
		try {
			String passcode = (String) request.getSession().getAttribute("randomcode");
			if(!(StringUtil.isNotBlank(passcode) && passcode.equalsIgnoreCase(admin.getCode()))){
				logger.info("验证码信息错误");
				response.getWriter().write("验证码错误");
				return;
			}
			if(!(StringUtil.isNotBlank(admin.getAdminName()) || StringUtil.isNotBlank(admin.getAdminPwd()))){
				logger.info("用户名密码不能为空");
				response.getWriter().write("用户名或密码不能为空");
				return;
			}
			Admin adminInfo = this.adminService.getAdminInfo(admin.getAdminName(), admin.getAdminPwd());
			if(adminInfo != null && StringUtil.isNotBlank(adminInfo.getAdminName())){
				//获取所有资源信息
				this.caseService.initList();
				request.getSession().setAttribute("admin", adminInfo);
				response.getWriter().write("success");
				logger.info(admin.getAdminName()+"登陆成功");
			}else{
				logger.info("用户名密码错误");
				response.getWriter().write("用户名或密码错误");
			}
		} catch (Exception e) {
			logger.debug("管理员登陆逻辑异常："+e);
		}
		logger.info("管理员逻辑处理完毕，耗时["+(System.currentTimeMillis() - starttime) +"]ms");
	}
	
	/**
	 * 登出逻辑处理
	 * @param request
	 * @return
	 */
	@RequestMapping("/loginOut")
	public String loginOut(HttpServletRequest request){
		if(request.getSession().getAttribute("admin") != null){
			logger.info("处理登出逻辑……");
			request.getSession().removeAttribute("admin");
		}
		logger.info("退出登录");
		return "login.html";
	}
	/**
	 * 读取网站配置信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/index")
	public String toIndex(HttpServletRequest request){
		logger.info("读取网站相关信息……");
		try {
			WebSite websiteInfo = this.adminService.getWebsitInfo();
			request.setAttribute("info", websiteInfo);
		} catch (Exception e) {
			logger.debug("读取网站信息异常，请联系开发人员");
		}
		return "info.jsp";
	}
	/**
	 * 更改管理员密码
	 * @param response
	 * @param request
	 */
	@RequestMapping("/upass")
	public void upass(HttpServletResponse response,HttpServletRequest request){
		logger.info("更改管理员密码");
		String mpass = request.getParameter("mpass");
		String newpass = request.getParameter("newpass");
		try {
			if(!StringUtil.isNotBlank(mpass)){
				response.getWriter().write("原密码不能为空！");
				return;
			}else{
				Admin admin = (Admin) request.getSession().getAttribute("admin");
				if(admin == null || !StringUtil.isNotBlank(admin.getAdminName())){
					response.getWriter().write("您还未登陆或登录已过期，请重新登录，没有修改权限");
					return;
				}else if(!admin.getAdminPwd().equals(mpass)){
					response.getWriter().write("输入原密码与系统原密码不匹配，请重新输入！！");
					return;
					
				}else{
					admin.setAdminPwd(newpass);
					int update = this.adminService.update(admin);
					if(update > 0){
						logger.info("更改成功");
						request.getSession().removeAttribute("admin");
						request.getSession().setAttribute("admin", admin);
						response.getWriter().write("密码更改成功");
					}else{
						response.getWriter().write("密码更改失败");
						
					}
				}
			}
		} catch (Exception e) {
			logger.debug("管理员信息更改异常："+e);
		}
	}
	
	/**
	 * 当首页内容有变化时，重新生成首页
	 * @throws IOException 
	 * */
	public void reCreateIndex() throws IOException{
		LogUtil.getLogger(getClass()).debug("start crate index.html...");
		Properties p = new Properties();
		String p_path = System.getProperty("webapp.root");
		if(!p_path.endsWith(File.separator))
			p_path += File.separator;
		p_path += "WEB-INF/config.properties";
		FileInputStream in = new FileInputStream(new File(p_path));
		p.load(in);
		String url = p.getProperty("init_url");
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(url);
		int code = client.executeMethod(method);
		if(code == HttpStatus.SC_OK){
			LogUtil.getLogger(getClass()).debug("success crate index.html...");
		}else{
			LogUtil.getLogger(getClass()).debug("fail crate index.html...");
		}
	}
	/**
	 * 更新网站配置信息
	 * @param website
	 * @param file
	 * @param request
	 * @param response
	 */
	@RequestMapping("/uwebsiteinfo")
	public void uwebsiteinfo(WebSite website,@RequestParam(value="file",required =false) CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response){
		logger.info("更改网站配置信息……");
		try {
			if(file != null && !file.isEmpty()){
				String type=file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));//读取文件后缀
				String fileName="logo_"+DateUtil.now(DateUtil.DATE_FORMAT_YYYYMMDDHHMMSS)+type;//取当前时间戳为文件名
				String path=request.getSession().getServletContext().getRealPath("/")+"/img/"+fileName;
				if(uploadFile(file,path)){
					website.setLogo("img/"+fileName);
				}else{
					response.getWriter().write("文件上传失败，请重新提交");
				}
			}
			String logo = this.adminService.getWebsitInfo().getLogo();
			String keyword = website.getKeyword();
			keyword = keyword.replaceAll("，", ",");
			if(keyword.endsWith(",")){
				keyword = keyword.substring(0, keyword.length()-1);
			}
			website.setKeyword(keyword);
			if(this.adminService.update(website) > 0){
				if(file != null)
					FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+logo);
				reCreateIndex();
				logger.info("更新成功");
				response.getWriter().write("更新成功");
			}else{
				logger.info("更新失败");
				response.getWriter().write("更新失败");
			}
		}  catch (Exception e) {
			logger.debug("网站配置信息异常"+e);
		}
	}
	/**
	 * 获取轮播图列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/adv")
	public String getAdv(HttpServletRequest request){
		logger.info("获取轮播图列表");
		Case c = new Case();
		c.setBelong(1);
		try {
			List<Case> list = this.caseService.getCase(c);
			request.setAttribute("advs", list);
		} catch (Exception e) {
			logger.debug("获取轮播图信息异常"+e);
		}
		return "adv.jsp";
	}
	/**
	 * 根据id获取资源信息
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/getAdvById")
	public String getAdvById(HttpServletRequest request) throws Exception{
		String id = request.getParameter("id");
		logger.info("获取id为"+id+"轮播图信息");
		try {
			request.setAttribute("adv", this.caseService.selectOne(Integer.parseInt(id)));
		} catch (NumberFormatException e) {
			logger.debug("数字转化异常："+e);
			throw new NumberFormatException("数字转化异常，请重新访问"+e);
		} catch (Exception e) {
			logger.debug("获取轮播图信息异常");
			throw new Exception("获取轮播图信息异常,请重新访问"+e);
		}
		return "advInfo.jsp";
	}
	/**
	 * 更新轮播图信息
	 * @param c
	 * @param file
	 * @param request
	 * @param response
	 */
	@RequestMapping("/uadvInfo")
	public void uadvInfo(Case c,@RequestParam(value="file",required =false) CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response){
		logger.info("轮播图信息变更……");
		try {
			if(!file.isEmpty()){
				String type=file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));//读取文件后缀
				String fileName="slides_"+DateUtil.now(DateUtil.DATE_FORMAT_YYYYMMDDHHMMSS)+type;//取当前时间戳为文件名
				String path=request.getSession().getServletContext().getRealPath("/")+"/img/slides/"+fileName;
				if(uploadFile(file,path)){
					c.setResource("img/slides/"+fileName);
				}else{
					response.getWriter().write("文件上传失败，请重新提交");
				}
			}
			if(StringUtil.isNotBlank(request.getParameter("id"))){
				c.setId(Integer.parseInt(request.getParameter("id")));
			}
			if(StringUtil.isNotBlank(request.getParameter("belong"))){
				c.setBelong(Integer.parseInt(request.getParameter("belong")));
			}
			String resource = this.caseService.selectOne(c.getId()).getResource();
			if (this.caseService.update(c) > 0) {
				if(file != null)
					FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
				reCreateIndex();
				logger.info("更新成功");
				response.getWriter().write("更新成功");
			} else {
				logger.info("更新失败");
				response.getWriter().write("更新失败");
			}
		}  catch (Exception e) {
			logger.debug("轮播图信息变更异常"+e);
		}
	}
	/**
	 * 添加轮播图信息
	 * @param c
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping("/addAdvInfo")
	public void addAdvInfo(Case c, @RequestParam(value = "img", required = false) CommonsMultipartFile file,
			HttpServletRequest request,HttpServletResponse response) {
		logger.info("添加/更新轮播图信息……");
		c.setBelong(1);
		try {
			if (!file.isEmpty()) {
				createCase(c, file, request, response, false);
			}
			int addorupdate = StringUtil.isNotBlank(request.getParameter("addorupdate")) ? Integer.parseInt(request.getParameter("addorupdate")) : 0;
			if(addorupdate == 0){
				if (this.caseService.addCase(c) > 0) {
					logger.info("添加成功");
					reCreateIndex();
					response.getWriter().write("添加成功");
				} else {
					logger.info("添加失败");
					response.getWriter().write("添加失败");
				}
			}else{
				if (this.caseService.update(c) > 0) {
					logger.info("更新成功");
					reCreateIndex();
					response.getWriter().write("更新成功");
				} else {
					logger.info("更新失败");
					response.getWriter().write("更新失败");
				}
			}
		} catch (Exception e) {
			logger.debug("添加/更新轮播图信息异常" + e);
			request.setAttribute("addRslt", "添加/更新轮播图信息异常，请重新添加");
		}
	}
	/**
	 * 根据id删除轮播图信息
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping("/delAdv")
	public void delAdvById(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String id = request.getParameter("id");
		logger.info("删除id="+id+"轮播图");
		try {
			if(StringUtil.isNotBlank(id)){
				int int_id = Integer.parseInt(id);
				Case c = new Case();
				c.setId(int_id);
				String resource = this.caseService.selectOne(int_id).getResource();
				int delete = this.caseService.delete(c);
				if(delete >0){
					FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
					reCreateIndex();
					logger.info("删除成功");
					response.getWriter().print("删除成功");
				}else{
					logger.info("删除失败");
					response.getWriter().print("删除失败");
				}
			}else{
				logger.info("轮播图id获取为空");
				response.getWriter().print("轮播图id为空");
			}
		}  catch (Exception e) {
			logger.debug("轮播图删除异常"+e);
			response.getWriter().print("轮播图删除异常，请重新访问");
		}
	}
	/**
	 * 获取服务相关信息列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/services")
	public String getServices(HttpServletRequest request){
		logger.info("获取服务相关信息^_^");
		Case c = new Case();
		c.setBelong(2);
		try {
			List<Case> list = this.caseService.getCase(c);
			request.setAttribute("services", list);
		} catch (Exception e) {
			logger.debug("获取服务列表信息异常"+e);
		}
		return "services.jsp";
	}
	/**
	 * 添加服务信息
	 * @param c
	 * @param files
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/addServices")
	public void addServices(Case c, @RequestParam(value = "file", required = false) CommonsMultipartFile[] files,
			HttpServletRequest request,HttpServletResponse response) throws IOException{
		String addOrUpdate = request.getParameter("addOrUpdate");
		if(addOrUpdate.equals("1")){
//			logger.info("更改服务信息");
			uservice(c, files, request, response);
		}else{
			logger.info("添加服务信息");
			try {
				c.setBelong(2);
				boolean isfm = false;
				if(files != null){
					if(files.length == 1){
						if(c.getIsneturl().equals("4"))
							isfm = true;
						createCase(c, files[0], request, response, isfm);
					}else if(files.length == 2){
						for (CommonsMultipartFile file : files) {
							createCase(c, file, request, response, true);
						}
					}
				}
				if(this.caseService.addCase(c) > 0){
					reCreateIndex();
					response.getWriter().write("服务信息添加完成");
				}else{
					response.getWriter().write("服务信息添加失败");
				}
			}  catch (Exception e) {
				logger.debug("服务信息添加异常"+e);
				response.getWriter().write("服务信息添加失败");
			}
		}
		
	}
	/**
	 * 更新服务信息
	 * @param c
	 * @param files
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/uservice")
	public void uservice(Case c, @RequestParam(value = "file", required = false) CommonsMultipartFile[] files,
			HttpServletRequest request,HttpServletResponse response) throws IOException{
		logger.info("更改服务信息");
		try {
			if(files != null){
				if(files.length == 1){
					createCase(c, files[0], request, response, false);
				}else if(files.length == 2){
					for (CommonsMultipartFile file : files) {
						createCase(c, file, request, response, true);
					}
				}
			}
			String resource = this.caseService.selectOne(c.getId()).getResource();
			if(this.caseService.update(c) > 0){
				if(files != null && files.length > 0)
					FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
				reCreateIndex();
				logger.info("服务信息更改完成");
				response.getWriter().write("服务信息更改完成");
			}else{
				logger.info("服务信息更改失败");
				response.getWriter().write("服务信息更改失败");
			}
		}  catch (Exception e) {
			logger.debug("服务信息添加异常"+e);
			response.getWriter().write("服务信息更改失败");
		}
//		return "services.do";
	}
	/**
	 * 根据id获取单个服务信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/getServiceById")
	public String getServiceById(HttpServletRequest request){
		logger.info("根据id获取服务具体信息");
		int id = Integer.parseInt(request.getParameter("id"));
		try {
			Case c = this.caseService.selectOne(id);
			request.setAttribute("caseInfo", c);
		} catch (Exception e) {
			logger.debug("根据id获取服务信息异常："+e);
		}
		return "serviceInfo.jsp";
	}
	/**
	 * 根据id删除服务信息
	 * @param request
	 * @param response
	 */
	@RequestMapping("/delServiceById")
	public void getServiceById(HttpServletRequest request,HttpServletResponse response){
		logger.info("根据id删除服务");
		int id = Integer.parseInt(request.getParameter("id"));
		try {
			if(id ==0){
				response.getWriter().print("未指定要删除的资源，删除失败");
				return;
			}
			String resource = this.caseService.selectOne(id).getResource();
			int delt = this.caseService.delete(new int[]{id});
			if(delt > 0){
				FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
				reCreateIndex();
				logger.info("删除成功");
				response.getWriter().print("删除成功");
			}else{
				response.getWriter().print("删除失败");
			}
		} catch (Exception e) {
			logger.debug("根据id删除服务："+e);
			try {
				response.getWriter().print("删除失败");
			} catch (IOException e1) {
				
			}
		}
	}
	/**
	 * 获取公司简介和公司成员信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/aboutus_1")
	public String getAboutUsInfo(HttpServletRequest request){
		logger.info("获取关于我们-公司简介信息");
		try {
			List<Case> case1 = this.caseService.getCase(new Case(3));
			List<Case> members = this.caseService.getCase(new Case(4));
			if(members.size() > 0){
				TypeHelper typeHelper = new TypeHelper();
				Map<String, String> rank = typeHelper.getMemberRankMap();
				Map<String, String> state = typeHelper.getMemberStateMap();
				for (Case c : members) {
					c.setIsneturlDesc(rank.get(String.valueOf(c.getIsneturl())));
					c.setFmResourceDesc(state.get(String.valueOf(c.getFmResource())));
				}
				request.setAttribute("members", members);
			}
			if(case1.size() > 0 ){
				request.setAttribute("aboutus", case1.get(0));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "aboutus.jsp";
	}
	/**
	 * 添加成员信息
	 * @param c
	 * @param file
	 * @param request
	 * @param response
	 */
	@RequestMapping("/addMember")
	public void addMemberInfo(Case c,@RequestParam(value="img",required = false) CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response){
		logger.info("添加成员信息");
		try {
			if(file != null){
				createCase(c, file, request, response, false);
				int addCase = this.caseService.addCase(c);
				if(addCase > 0){
					logger.info("添加成功");
					response.getWriter().print("添加成功");
				}else{
					response.getWriter().print("添加失败");
				}
			}
		} catch (Exception e) {
			logger.debug("添加成员信息异常："+e);
		}
	}
	/**
	 * 更新成员信息
	 * @param c
	 * @param file
	 * @param request
	 * @param response
	 */
	@RequestMapping("/updateMember")
	public void updateMemberInfo(Case c,@RequestParam(value="img",required = false) CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response){
		logger.info("更新成员信息");
		try {
			if(file != null){
				createCase(c, file, request, response, false);
				String resource = this.caseService.selectOne(c.getId()).getResource();
				int addCase = this.caseService.update(c);
				if(addCase > 0){
					FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
					logger.info("修改成功");
					response.getWriter().print("修改成功");
				}else{
					response.getWriter().print("修改失败");
				}
			}
		} catch (Exception e) {
			logger.debug("修改成员信息异常："+e);
		}
	}
	/**
	 * 删除成员信息
	 * @param request
	 * @param response
	 */
	@RequestMapping("/delMemberById")
	public void addMemberInfo(HttpServletRequest request,HttpServletResponse response){
		logger.info("删除成员信息");
		int id = StringUtil.isNotBlank(request.getParameter("id")) ? Integer.parseInt(request.getParameter("id")) : 0;
		try {
			if(id != 0){
				String resource = this.caseService.selectOne(id).getResource();
				int del = this.caseService.delete(new int[]{id});
				if(del > 0){
					FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
					logger.info("删除成功");
					response.getWriter().print("删除成功");
				}else{
					response.getWriter().print("删除失败");
				}
			}
		} catch (Exception e) {
			logger.debug("删除成员信息异常："+e);
		}
	}
	/**
	 * 根据id获取成员信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/getMemberById")
	public String getMemberInfo(HttpServletRequest request){
		logger.info("获取成员信息");
		int id = StringUtil.isNotBlank(request.getParameter("id")) ? Integer.parseInt(request.getParameter("id")) : 0;
		try {
			if(id != 0){
				Case member = this.caseService.selectOne(id);
				if(member != null ){
					request.setAttribute("member", member);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "memberInfo.jsp";
	}
	/**
	 * 修改公司简介
	 * @param c
	 * @param file
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/aboutus")
	public String aboutus(Case c,@RequestParam(value = "file", required = false) CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response){
		logger.info("添加/修改公司简介信息");
		String strId = StringUtil.isNotBlank(String.valueOf(c.getId())) ? String.valueOf(c.getId()) : null;
		int update = 0;
		String resource = "";
		try {
			createCase(c, file, request, response, false);
		if(!StringUtil.isNotBlank(strId) || c.getId() == 0){
			logger.info("添加公司简介");
			update = this.caseService.save(new Case[]{c});
		}else{
			resource = this.caseService.selectOne(c.getId()).getResource();
			update = this.caseService.update(c);
			if(update > 0){
				if(file != null && file.getSize() != 0)
					FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
			}
		}
		if(update > 0){
			logger.info("添加/更新成功");
			reCreateIndex();
			request.setAttribute("addRslt", "添加/更新成功");
		}else{
			request.setAttribute("addRslt", "添加/更新失败");
		}
		} catch (Exception e) {
			logger.debug("更新异常："+e);
			request.setAttribute("addRslt", "添加/更新失败");
		}
		return "aboutus_1.do";
	}
	/**
	 * 获取留言列表
	 * @param c
	 * @param file
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/book")
	public String getBookInfos(Case c,@RequestParam(value = "file", required = false) CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response){
		logger.info("获取留言列表信息");
		try {
			List<Case> list = this.caseService.getCase(new Case(5));
			for (Case c1 : list) {
				c1.setCreatetime(DateUtil.formatDate(c1.getCreatetime(), DateUtil.DATE_FORMAT_CN_YYYYMMDD));
			}
			request.setAttribute("books", list);
		} catch (Exception e) {
			logger.debug("获取留言列表信息异常："+e);
		}
		return "book.jsp";
	}
	/**
	 * 删除留言信息
	 * @param request
	 * @param response
	 */
	@RequestMapping("/delBook")
	public void delBook(HttpServletRequest request,HttpServletResponse response){
		logger.info("删除留言");
		String[] idvalues = request.getParameterValues("id");
		int[] id = new int[idvalues.length];
		try {
			if(idvalues.length != 0){
				for(int i=0;i<idvalues.length;i++){
					id[i] = Integer.parseInt(idvalues[i]);
				}
				int del = this.caseService.delete(id);
				if(del > 0){
					logger.info("删除成功");
					response.getWriter().print("删除成功");
				}else{
					logger.info("删除失败");
					response.getWriter().println("删除失败");
				}
			}else{
				response.getWriter().println("id为0，请重新选择");
			}
		} catch (Exception e) {
			logger.debug("删除信息异常："+e);
		}
	}
	@RequestMapping("/serverpoint")
	public String getServerPointInfo(HttpServletRequest request){
		logger.info("获取服务网点信息");
		try {
			List<Case> list = this.caseService.getCase(new Case(6));
			if(list.size() > 0){
				for (Case c : list) {
					if(c.getFmResource().indexOf("/") > -1){
						c.setFmResourceDesc(c.getFmResource().substring(0,c.getFmResource().lastIndexOf("/")));
						String[] isnetds = c.getFmResource().substring(0, c.getFmResource().lastIndexOf("/")).split("/");;
						c.setIsneturlDesc(isnetds[0]);
					}
				}
			}
			request.setAttribute("list", list);
		} catch (Exception e) {
			logger.debug("获取服务网点信息异常："+e);
		}
		return "serverpoint.jsp";
	}
	@RequestMapping("/delSPById")
	public void updateServerPointInfo(HttpServletRequest request,HttpServletResponse response){
		logger.info("删除服务网点信息");
		try {
			int id = StringUtil.isNotBlank(request.getParameter("id")) ? Integer.parseInt(request.getParameter("id")) : 0;
			if(id != 0){
				Case selectOne = this.caseService.selectOne(id);
				String resource = selectOne.getResource();
				int update = this.caseService.delete(new int[]{id});
				if(update > 0){
					FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
					reCreateIndex();
					logger.info("删除成功");
					response.getWriter().print("删除成功");
				}else{
					logger.info("删除失败");
					response.getWriter().print("删除失败");
				}
			}else{
				logger.info("id为0");
				response.getWriter().print("删除失败");
			}
		} catch (Exception e) {
			logger.debug("删除服务网点信息异常："+e);
		}
	}
	@RequestMapping("/addServerPoint")
	public void addServerPointInfo(Case c,@RequestParam(value = "file", required = false) CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response){
		logger.info("添加/更新服务网点信息");
		try {
			c.setBelong(6);
			if(file != null){
				createCase(c, file, request, response, false);
			}
			int id = c.getId();
			int update = 0;
			if(id == 0){
				update = this.caseService.save(new Case[]{c});
				if(update > 0){
					reCreateIndex();
					logger.info("添加成功"); 
					response.getWriter().print("添加成功");
				}else{
					logger.info("添加失败");
					response.getWriter().print("添加失败");
				}
			}else{
				Case selectOne = this.caseService.selectOne(id);
				String resource = selectOne.getResource();
				update = this.caseService.update(c);
				if(update > 0){
					if(file != null && file.getSize() > 0)
						FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
					reCreateIndex();
					logger.info("修改成功");
					response.getWriter().print("修改成功");
				}else{
					logger.info("修改失败");
					response.getWriter().print("修改失败");
				}
			}
		} catch (Exception e) {
			logger.debug("添加/修改服务网点信息异常："+e);
		}
	}
	
	@RequestMapping("/news")
	public String getAllNews(HttpServletRequest request){
		logger.info("获取新闻信息");
		try {
			List<Case> list = this.caseService.getCase(new Case(7));
			if(list.size() > 0){
				for (Case case1 : list) {
					case1.setCreatetime(DateUtil.formatDate(case1.getCreatetime(), DateUtil.DATE_FORMAT_CN_YYYYMMDD));
				}
			}
			request.setAttribute("news", list);
		} catch (Exception e) {
			logger.debug("获取新闻信息异常："+e);
		}
		return "news.jsp";
	}
	@RequestMapping("addorupdateNews")
	public void addOrUpdateNews(Case c,@RequestParam(value="file",required=false) CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response){
		int id = c.getId();
		c.setBelong(7);
		try {
			if(file != null){
				createCase(c, file, request, response, false);
			}
			if(id == 0 ){
				logger.info("添加新闻");
				int addCase = this.caseService.addCase(c);
				if(addCase >0){
					logger.info("添加新闻成功");
					response.getWriter().print("添加成功");
				}else{
					logger.debug("添加新闻失败");
					response.getWriter().print("添加失败");
				}
			}else{
				logger.info("更新新闻信息");
				String resource = this.caseService.selectOne(id).getResource();
				int update = this.caseService.update(c);
				if(update >0){
					if(file != null)
						FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
					logger.info("修改新闻成功");
					response.getWriter().print("修改成功");
				}else{
					logger.debug("修改新闻失败");
					response.getWriter().print("修改失败");
				}
			}
		} catch (Exception e) {
			logger.debug("添加或修改新闻异常："+e);
		}
	}
	@RequestMapping("delNews")
	public void delNewsById(HttpServletRequest request,HttpServletResponse response){
		String strId = request.getParameter("id");
		try {
			if(StringUtil.isNotBlank(strId)){
				String resource = this.caseService.selectOne(Integer.parseInt(strId)).getResource();
				int del = this.caseService.delete(new int[]{Integer.parseInt(strId)});
				if(del >0){
					FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
					logger.info("删除新闻成功");
					response.getWriter().print("删除成功");
				}else{
					logger.debug("删除新闻失败");
					response.getWriter().print("删除失败");
				}
			}else{
				logger.debug("id为空");
				response.getWriter().print("删除失败，id为空");
			}
		} catch (Exception e) {
			logger.debug("输出新闻信息异常："+e);
		}
	}
	@RequestMapping("/prices")
	public String getPrices(HttpServletRequest request){
		logger.info("获取价目表信息");
		try {
			List<Case> case1 = this.caseService.getCase(new Case(8));
			if(case1.size() > 0){
				for (Case case2 : case1) {
					case2.setIsneturlDesc(new TypeHelper().getPriceMap().get(case2.getIsneturl()));
				}
			}
			request.setAttribute("price", case1);
		} catch (Exception e) {
			logger.debug("获取价目信息异常："+e);
		}
		return "prices.jsp";
	}
	@RequestMapping("/addOrUpdatePrice")
	public void addOrUpdatePrice(Case c,@RequestParam(value="file",required=false) CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response){
		int id = c.getId();
		try {
			c.setBelong(8);
			if(file != null){
				createCase(c, file, request, response, false);
			}
			if(id == 0){
				logger.info("添加产品信息");
				int addCase = this.caseService.addCase(c);
				if(addCase > 0){
					int size = this.caseService.select(new Case(8), null).size();
					if(size <5){
						reCreateIndex();
					}
					logger.info("添加成功");
					response.getWriter().print("添加成功");
				}else{
					logger.info("添加失败");
					response.getWriter().print("添加失败");
					
				}
			}else{
				logger.info("修改产品信息");
				String resource = this.caseService.selectOne(id).getResource();
				int addCase = this.caseService.update(c);
				if(addCase > 0){
					if(file != null){
						FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
					}
					logger.info("修改成功");
					int size = this.caseService.select(new Case(8), null).size();
					if(size <5){
						reCreateIndex();
					}
					response.getWriter().print("修改成功");
				}else{
					logger.info("修改失败");
					response.getWriter().print("修改失败");
					
				}
			}
		}  catch (Exception e) {
			logger.debug("添加或修改产品信息异常："+e);
		}
	}
	@RequestMapping("/delPrice")
	public void delPrice(int id,HttpServletRequest request,HttpServletResponse response){
		logger.info("删除价目信息");
		try {
			String resource = this.caseService.selectOne(id).getResource();
			int del = this.caseService.delete(new int[]{id});
			if(del > 0){
				logger.info("删除成功");
				int size = this.caseService.select(new Case(8), null).size();
				if(size <5){
					reCreateIndex();
				}
				FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
				response.getWriter().print("删除成功");
			}else{
				logger.info("删除失败");
				response.getWriter().print("删除失败");
				
			}
		} catch (Exception e) {
			logger.debug("删除价目信息异常："+e);
		}
	}
	
	/**
	 * 获取服务相关信息列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/examples")
	public String getExamples(HttpServletRequest request){
		logger.info("获取修复实例相关信息^_^");
		Case c = new Case();
		c.setBelong(9);
		try {
			List<Case> list = this.caseService.getCase(c);
			c.setBelong(2);
			List<Case> services = this.caseService.getCase(c);
			for (Case case1 : list) {
				for (Case case2 : services) {
					if(case2.getId() == case1.getParentId()){
						case1.setParent(case2);
						break;
					}
				}
			}
			request.setAttribute("examples", list);
			request.setAttribute("services", services);
		} catch (Exception e) {
			logger.debug("获取服务列表信息异常"+e);
		}
		return "examples.jsp";
	}
	/**
	 * 添加修复实例
	 * @param c
	 * @param files
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/addExamples")
	public void addExample(Case c, @RequestParam(value = "file", required = false) CommonsMultipartFile[] files,
			HttpServletRequest request,HttpServletResponse response) throws IOException{
		String addOrUpdate = request.getParameter("addOrUpdate");
		if(addOrUpdate.equals("1")){
//			logger.info("更改服务信息");
			uexample(c, files, request, response);
		}else{
			logger.info("添加修复实例");
			try {
				c.setBelong(9);
				boolean isfm = false;
				if(files != null){
					if(files.length == 1){
						if(c.getIsneturl().equals("4"))
							isfm = true;
						createCase(c, files[0], request, response, isfm);
					}else if(files.length == 2){
						for (CommonsMultipartFile file : files) {
							createCase(c, file, request, response, true);
						}
					}
				}
				if(this.caseService.addCase(c) > 0){
					response.getWriter().write("修复实例添加完成");
				}else{
					response.getWriter().write("修复实例添加失败");
				}
			}  catch (Exception e) {
				logger.debug("修复实例添加异常"+e);
				response.getWriter().write("修复实例信息添加失败");
			}
		}
	}
	/**
	 * 更新修复实例信息
	 * @param c
	 * @param files
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/uexample")
	public void uexample(Case c, @RequestParam(value = "file", required = false) CommonsMultipartFile[] files,
			HttpServletRequest request,HttpServletResponse response) throws IOException{
		logger.info("更改修复实例");
		try {
			if(files != null){
				if(files.length == 1){
					createCase(c, files[0], request, response, false);
				}else if(files.length == 2){
					for (CommonsMultipartFile file : files) {
						createCase(c, file, request, response, true);
					}
				}
			}
			Case selectOne = this.caseService.selectOne(c.getId());
			String resource = selectOne.getResource();
			if(this.caseService.update(c) > 0){
				if(files.length > 0){
					FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
				}
				logger.info("修复实例更改完成");
				response.getWriter().write("修复实例更改完成");
			}else{
				logger.info("修复实例更改失败");
				response.getWriter().write("修复实例更改失败");
			}
		}  catch (Exception e) {
			logger.debug("修复实例添加异常"+e);
			response.getWriter().write("修复实例更改失败");
		}
//		return "services.do";
	}
	/**
	 * 根据id获取单个修复实例信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/getExampleById")
	public String getExampleById(HttpServletRequest request){
		logger.info("根据id获取修复实例具体信息");
		int id = Integer.parseInt(request.getParameter("id"));
		try {
			Case c = this.caseService.selectOne(id);
			if(null == c.getParent()){
				c.setParent(this.caseService.selectOne(c.getParentId()));
			}
			request.setAttribute("bbs", this.caseService.getBBSInfoByCaseId(id));
			request.setAttribute("caseInfo", c);
		} catch (Exception e) {
			logger.debug("根据id获取修复实例具体信息异常："+e);
		}
		return "exampleInfo.jsp";
	}
	/**
	 * 根据id删除修复实例
	 * @param request
	 * @param response
	 */
	@RequestMapping("/delExampleById")
	public void getExampleById(HttpServletRequest request,HttpServletResponse response){
		logger.info("根据id删除删除实例");
		int id = Integer.parseInt(request.getParameter("id"));
		try {
			if(id ==0){
				response.getWriter().print("未指定要删除的资源，删除失败");
				return;
			}
			Case selectOne = this.caseService.selectOne(id);
			String resource = selectOne.getResource();
			int delt = this.caseService.delete(new int[]{id});
			if(delt > 0){
				FileHelper.delLocalFile(request.getSession().getServletContext().getRealPath("/")+"/"+resource);
				logger.info("删除成功");
				response.getWriter().print("删除成功");
			}else{
				response.getWriter().print("删除失败");
			}
		} catch (Exception e) {
			logger.debug("根据id删除修复："+e);
			try {
				response.getWriter().print("删除失败");
			} catch (IOException e1) {
				
			}
		}
	}
	/**
	 * 根据id删除评论
	 * @param request
	 * @param response
	 */
	@RequestMapping("/delBBSById")
	public void delBBSById(HttpServletRequest request,HttpServletResponse response){
		logger.info("根据id删除评论");
		int id = Integer.parseInt(request.getParameter("id"));
		try {
			if(id ==0){
				response.getWriter().print("未指定要删除的评论，删除失败");
				return;
			}
			int delt = this.caseService.delBBSById(id);
			if(delt > 0){
				logger.info("删除成功");
				response.getWriter().print("删除成功");
			}else{
				response.getWriter().print("删除失败");
			}
		} catch (Exception e) {
			logger.debug("根据id删除评论："+e);
			try {
				response.getWriter().print("删除失败");
			} catch (IOException e1) {
				
			}
		}
	}
	
	/**
	 * 文件处理，并将处理结果设置到Case对象
	 * @param c
	 * @param file
	 * @param request
	 * @param response
	 * @param isfm
	 * @throws IOException
	 */
	private void createCase(Case c,CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response,boolean isfm) throws IOException{
		String type = "";
		String fileName = "";
		String dbpath = "";
		String path = "";
		if (file == null || file.isEmpty() || file.getSize() == 0) {
			logger.info("文件为空,跳过，直接返回");
			return;
		} else {
			type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1).toLowerCase();// 读取文件后缀
		}
		if (type.equals("jpg") || type.equals("png") || type.equals("bmp") || type.equals("jpeg")
				|| type.equals("gif")) {
			fileName = "img_" + DateUtil.now(DateUtil.DATE_FORMAT_YYYYMMDDHHMMSS) + "." + type;// 取当前时间戳为文件名
			path = request.getSession().getServletContext().getRealPath("/") + "/img/" + fileName;
			dbpath = "img/" + fileName;
			if (!isfm) {
				c.setType(1);
				c.setTypeName(new TypeHelper().getMap().get("1"));
				c.setResource(dbpath);
			}else {
				c.setFmResource(dbpath);
			}
		} else if (type.equals("3gp") || type.equals("avi") || type.equals("wmv") || type.equals("mpeg")
				|| type.equals("mkv") || type.equals("rmvb") || type.equals("mov") || type.equals("swf")
				|| type.equals("flv")) {
			c.setType(3);
			c.setTypeName(new TypeHelper().getMap().get("3"));
			fileName = "swf_" + DateUtil.now(DateUtil.DATE_FORMAT_YYYYMMDDHHMMSS) + "." + type;// 取当前时间戳为文件名
			path = request.getSession().getServletContext().getRealPath("/") + "/img/vedio/" + fileName;
			dbpath = "img/vedio/" + fileName;
			c.setResource(dbpath);

		} else if (type.equals("mp4") || type.equals("webm") || type.equals("ogg")) {
			c.setType(2);
			c.setTypeName(new TypeHelper().getMap().get("2"));
			fileName = "vedio_" + DateUtil.now(DateUtil.DATE_FORMAT_YYYYMMDDHHMMSS) + "." + type;// 取当前时间戳为文件名
			path = request.getSession().getServletContext().getRealPath("/") + "/img/vedio/" + fileName;
			dbpath = "img/vedio/" + fileName;
			c.setResource(dbpath);

		} else {
			response.getWriter().write("不支持该文件类型，请重新上传");
			return;
		}
		if (!uploadFile(file, path)) {
			response.getWriter().write("文件上传失败，请重新提交");
			return;
		}
	}
	@RequestMapping("/UserArticleFileUpload")
	public void UserArticleFileUpload(@RequestParam(value = "upload") CommonsMultipartFile file,
			HttpServletRequest request,HttpServletResponse response){
		logger.info("富文本文件上传");
		try {
			 // CKEditor提交的很重要的一个参数  
	        String callback = request.getParameter("CKEditorFuncNum");
			String type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1).toLowerCase();// 读取文件后缀
			PrintWriter writer = response.getWriter();
			if(!StringUtil.isNotBlank(TypeHelper.getFileTypeMap().get(type))){
				writer.println("<script type=\"text/javascript\">");
				writer.println("window.parent.CKEDITOR.tools.callFunction(" + callback  
	                    + ",''," + "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');");
				writer.println("</script>");
				writer.flush();
		        writer.close();
				return;
			}
			String path = System.getProperty("webapp.root");//项目绝对路径
			String img_path = request.getContextPath()+"/";
			String relative_path = "img/resource_" + DateUtil.now(DateUtil.DATE_FORMAT_YYYYMMDDHHMMSS)+"."+type;
			String img_path_ie = img_path.concat(relative_path);
			path += relative_path;
			if(uploadFile(file, path)){
				// 返回"图像"选项卡并显示图片  request.getContextPath()为web项目名   
				logger.info("上传成功，文件相对路径："+path);
		        response.setContentType("text/html;charset=UTF-8");
				writer.println("<script type=\"text/javascript\">");  
		        writer.println("window.parent.CKEDITOR.tools.callFunction(" + callback  
		        		+ ",'" + img_path_ie + "','')"); 
		        writer.println("</script>");
		        writer.flush();
		        writer.close();
			}
		} catch (IOException e) {
			logger.error("文件上传异常："+e);
		}
	}
	/**
	 * 文件上传
	 * @param file
	 * @param path
	 * @return
	 */
	private boolean uploadFile(CommonsMultipartFile file, String path) {
		// TODO Auto-generated method stub
		File destFile = new File(path);
		boolean success = false;
		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);//复制临时文件到指定目录下
			//查看文件文件是否已经存在
			success = destFile.exists();
		} catch (IOException e) {
			logger.debug("文件上传异常");
		}
		return success;
	}
}
